

const { ccclass, property, executeInEditMode, menu, requireComponent } = cc._decorator;

@ccclass
@requireComponent(cc.Animation)
@requireComponent(cc.Sprite)
@menu('cccframework/' + FrameAnimator.name)
export default class FrameAnimator extends cc.Component {

    @property
    animatorName: string = 'default';
    @property
    frameRate: number = 5;
    @property
    _duration: number = -1;
    @property
    get duration(): number {
        return this._duration;
    }
    set duration(v: number) {
        this._duration = v;
        if (this.clip) {
            this.clip.duration = v;
        }
    }
    _isPlayAnim: boolean = false;
    get isPlayAnim(): boolean {
        return this._isPlayAnim;
    }
    set isPlayAnim(v: boolean) {
        this._isPlayAnim = v;
        if (v) {
            this.play();
        } else {
            this.stop();
        }
    }
    @property([cc.SpriteFrame])
    spfList: cc.SpriteFrame[] = [];
    @property
    isOnloadAutoPlay: boolean = false;
    // 播放次数
    @property({ type: cc.WrapMode })
    wrapMode: number = cc.WrapMode.Default;
    clip: cc.AnimationClip = null;
    
    
    get sprite(): cc.Sprite {
        return this.node.getComponent(cc.Sprite)
    }
    get anim(): cc.Animation {
        return this.node.getComponent(cc.Animation)
    }

    onLoad() {
        if (!CC_EDITOR && this.isOnloadAutoPlay) {
            this.isPlayAnim = true;
        }
    }
    initClip() {
        if (!this.clip && this.spfList.length > 0) {
            let clip = cc.AnimationClip.createWithSpriteFrames(this.spfList, this.frameRate);
            clip.wrapMode = this.wrapMode;
            clip.name = this.animatorName;
            this.anim.addClip(clip)
            if (this.duration > 0) {
                this.duration = this.duration;
            }
            this.clip = clip;
        }
    }
    play() {
        this.initClip();
        if (this.clip) {
            this.anim.play(this.clip.name);
        }
    }
    pause() {
        if (this.clip) {
            this.anim.stop(this.clip.name);
            console.log('停止动画', this.clip.name);
        }
    }
    stop() {
        this.pause();
        if (this.sprite) {
            this.sprite.spriteFrame = null;
        }
    }
}
